<?php
namespace application\admin\controllers\api;

use mz\behaviors\NoCsrf;
use mz\controllers\AdminController as Controller;
use mz\models\UploadFile;
use Yii;

/**
 * 图片处理类
 * Class UploadController
 * @package backend\controllers\api
 */
class UploadController extends Controller
{
    public function behaviors()
    {
        return [
            'csrf' => [
                'class' => NoCsrf::className(),
                'controller' => $this,
                'actions' => [
                    'content'
                ]
            ]
        ];
    }

    # 上传封面
    public function actionIndex()
    {
        $post = Yii::$app->request->post();
        if (empty($post['category']))$this->ajaxReturn([
                'state' => 0,
                'message' => '请求参数错误'
            ]);

        #category 上传文件类型image 图片
        #action 文件所属栏目
        #name 文件名称
        $post = array_filter($post,function($key){
            return in_array($key,['category','action','name']);
        },ARRAY_FILTER_USE_KEY);

        $res = UploadFile::uploadFiles('file',$post['category'],$post['action']);

        /**
         * $rs = [
         *      'source_name' => "源文件的名称",
         *      'thumb_name' => "缩略图的名称",
         * ]
         */
        $picUrl = empty($res['url']) || empty($res['source_name']) ? [] : $res['url'].$res['source_name'];
        $thumbUrl = empty($res['url']) || empty($res['thumb_name']) ? [] : $res['url'].$res['thumb_name'];
        $returnData = !empty($picUrl) ? ['state' => 'SUCCESS','path' => $picUrl,'thumb' => $thumbUrl] : ['state' => 0 , 'path' => '上传失败'];
        $this->ajaxReturn($returnData);
    }


    # 上传到内容
    public function actionContent()
    {

        $post['category'] = 'image';
        $post['action'] = 'article';

        $res = UploadFile::uploadFiles('file',$post['category'],$post['action']);

        /**
         * $rs = [
         *      'source_name' => "源文件的名称",
         *      'thumb_name' => "缩略图的名称",
         * ]
         */
        $picUrl = empty($res['url']) || empty($res['source_name']) ? [] : $res['url'].$res['source_name'];
        $thumbUrl = empty($res['url']) || empty($res['thumb_name']) ? [] : $res['url'].$res['thumb_name'];

//        {
//            "code": 0 //0表示成功，其它失败
//  ,"msg": "" //提示信息 //一般上传失败后返回
//  ,"data": {
//            "src": "图片路径"
//    ,"title": "图片名称" //可选
//  }
//}


        $returnData = !empty($picUrl) ? [
            'code' => 0,
            'msg' => '恭喜您上传成功',
            'data' => [
                'src' => 'http://img.mzcms.com/'.$picUrl,
                'title' => $res['source_name']
            ],
        ] : [
            'code' => 0,
            'msg' => '很遗憾，上传失败',
            'data' => [
                'src' => '',
                'title' => ''
            ],
        ];

        $this->ajaxReturn($returnData);
    }
}